package com.example.appusagestats

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.appusagestats.adapter.AppUsageAdapter
import com.example.appusagestats.manager.AppUsageStatsManager
import com.example.appusagestats.model.AppUsageInfo
import com.example.appusagestats.model.TimeSlot
import kotlinx.coroutines.*

class TimeSlotActivity : AppCompatActivity() {

    private lateinit var usageStatsManager: AppUsageStatsManager
    private lateinit var appUsageAdapter: AppUsageAdapter
    private lateinit var timeSlotRecyclerView: RecyclerView
    private lateinit var emptyTimeSlotText: TextView
    private lateinit var morningButton: Button
    private lateinit var afternoonButton: Button
    private lateinit var eveningButton: Button
    private lateinit var nightButton: Button

    private var currentTimeSlot = TimeSlot.MORNING
    private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_time_slot)

        try {
            // 分步初始化，每步都有错误处理
            initViews()
            initUsageStatsManager()
            setupRecyclerView()
            setupClickListeners()
            updateButtonSelection()
            
            // 延迟加载数据，确保界面完全初始化
            coroutineScope.launch {
                delay(100) // 短暂延迟确保界面渲染完成
                loadTimeSlotData(currentTimeSlot)
            }
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "onCreate error: ${e.message}", e)
            Toast.makeText(this, "初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        coroutineScope.cancel()
    }

    private fun initViews() {
        try {
            timeSlotRecyclerView = findViewById(R.id.timeSlotRecyclerView)
            emptyTimeSlotText = findViewById(R.id.emptyTimeSlotText)
            morningButton = findViewById(R.id.morningButton)
            afternoonButton = findViewById(R.id.afternoonButton)
            eveningButton = findViewById(R.id.eveningButton)
            nightButton = findViewById(R.id.nightButton)

            // 设置工具栏
            val toolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)
            setSupportActionBar(toolbar)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
            toolbar.setNavigationOnClickListener {
                finish()
            }
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "initViews error: ${e.message}", e)
            throw e
        }
    }

    private fun initUsageStatsManager() {
        try {
            usageStatsManager = AppUsageStatsManager(this)
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "initUsageStatsManager error: ${e.message}", e)
            throw e
        }
    }

    private fun setupRecyclerView() {
        try {
            appUsageAdapter = AppUsageAdapter(emptyList()) { appUsage ->
                try {
                    val intent = Intent(this, AppDetailActivity::class.java).apply {
                        putExtra("package_name", appUsage.packageName)
                        putExtra("app_name", appUsage.appName)
                    }
                    startActivity(intent)
                } catch (e: Exception) {
                    Log.e("TimeSlotActivity", "startActivity error: ${e.message}", e)
                    Toast.makeText(this, "打开应用详情失败", Toast.LENGTH_SHORT).show()
                }
            }

            timeSlotRecyclerView.apply {
                layoutManager = LinearLayoutManager(this@TimeSlotActivity)
                adapter = appUsageAdapter
            }
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "setupRecyclerView error: ${e.message}", e)
            throw e
        }
    }

    private fun setupClickListeners() {
        try {
            morningButton.setOnClickListener {
                currentTimeSlot = TimeSlot.MORNING
                loadTimeSlotData(TimeSlot.MORNING)
                updateButtonSelection()
            }

            afternoonButton.setOnClickListener {
                currentTimeSlot = TimeSlot.AFTERNOON
                loadTimeSlotData(TimeSlot.AFTERNOON)
                updateButtonSelection()
            }

            eveningButton.setOnClickListener {
                currentTimeSlot = TimeSlot.EVENING
                loadTimeSlotData(TimeSlot.EVENING)
                updateButtonSelection()
            }

            nightButton.setOnClickListener {
                currentTimeSlot = TimeSlot.NIGHT
                loadTimeSlotData(TimeSlot.NIGHT)
                updateButtonSelection()
            }
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "setupClickListeners error: ${e.message}", e)
            throw e
        }
    }

    private fun updateButtonSelection() {
        try {
            // 重置所有按钮样式
            morningButton.alpha = 0.7f
            afternoonButton.alpha = 0.7f
            eveningButton.alpha = 0.7f
            nightButton.alpha = 0.7f

            // 高亮当前选中的时间段
            when (currentTimeSlot) {
                TimeSlot.MORNING -> morningButton.alpha = 1.0f
                TimeSlot.AFTERNOON -> afternoonButton.alpha = 1.0f
                TimeSlot.EVENING -> eveningButton.alpha = 1.0f
                TimeSlot.NIGHT -> nightButton.alpha = 1.0f
            }
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "updateButtonSelection error: ${e.message}", e)
        }
    }

    private fun loadTimeSlotData(timeSlot: TimeSlot) {
        coroutineScope.launch {
            try {
                val data = withContext(Dispatchers.IO) {
                    usageStatsManager.getAppUsageStatsByTimeSlot(timeSlot)
                }
                
                updateUI(data)
            } catch (e: Exception) {
                Log.e("TimeSlotActivity", "loadTimeSlotData error: ${e.message}", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@TimeSlotActivity, "加载数据失败: ${e.message}", Toast.LENGTH_SHORT).show()
                    updateUI(emptyList())
                }
            }
        }
    }

    private fun updateUI(data: List<AppUsageInfo>) {
        try {
            if (data.isEmpty()) {
                emptyTimeSlotText.visibility = View.VISIBLE
                timeSlotRecyclerView.visibility = View.GONE
            } else {
                emptyTimeSlotText.visibility = View.GONE
                timeSlotRecyclerView.visibility = View.VISIBLE
                appUsageAdapter.updateData(data)
            }
        } catch (e: Exception) {
            Log.e("TimeSlotActivity", "updateUI error: ${e.message}", e)
            Toast.makeText(this, "更新界面失败", Toast.LENGTH_SHORT).show()
        }
    }
} 